package com.ai.study.service;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.ai.study.config.AiConfig;
import com.alibaba.fastjson2.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class OpenAiService {

    @Autowired
    private AiConfig aiConfig;

    public JSONObject chatByAcs(JSONObject chatParam) {
        // 构建请求GPT参数请求
        JSONObject request = new JSONObject();
        request.put("model", chatParam.getOrDefault("model", "text-davinci-003"));
        request.put("prompt", chatParam.getString("prompt"));
        request.put("max_tokens", chatParam.getOrDefault("max_tokens", 150));
        request.put("temperature", chatParam.getOrDefault("temperature", 0.7));
        HttpRequest httpRequest = HttpUtil.createPost(aiConfig.getOpenApiUrl())
                .bearerAuth(aiConfig.getOpenApiKey())
                .contentType("application/json")
                .body(request.toJSONString());
        try (HttpResponse response = httpRequest.execute()) {
            String body = response.body();
            return JSONObject.parseObject(body);
        } catch (Exception e) {
            log.error("请求gpt接口参数异常,request:{}, errMsg:{}", request, e.getMessage());
            return null;
        }
    }

}
